/**
 * Created by Delicate on 2018/1/3.
 */
import React from 'react';
import {
    StyleSheet,
    View,
    Text,
    DeviceEventEmitter
} from 'react-native';

import {
    FormStatus,
    FormEvent,
    SubmitBtn
} from '../../components/Form'

import NavBar from '../../components/NavBarView'
import HorizontalMenu from '../../components/HorizontalMenuView'
import ManagerService from '../../services/Manager'
import Constants from '../../config/Constants'

let _self = null;

const validRule = {
    base: {
        institution_name: {
            required: true,
        },
        busniess_number: {
            required: true,
            regExp: /^[0-9A-Za-z]{18,18}$/,
            errorMsg: '请输入18位营业执照号'
        },
        legal_name: {
            required: true,
        },
        industry_type: {
            required: true,
        },
        nature: {
            required: true,
        },
        registered_capital: {
            required: true,
            regExp: /^(\d|[1-9]\d+)(\.\d{1,4})?$/,
            errorMsg: '请输入不超过4位小数的注册资本'
        },
        establishment_date: {
            required: true,
        },
        province: {
            required: true,
        },
        city: {
            required: true,
        },
        district: {
            required: true,
        },
        detail_address: {
            required: true,
        },
        business: {
            required: true,
        },
        advantage: {
            required: false,
        },
    },
    contact: {
        the_applicant: {
            required: true,
        },
        the_applicant_job: {
            required: true,
        },
        the_applicant_mobile: {
            required: true,
            regExp: /1\d{10}/,
            errorMsg: '请输入合法的手机号码'
        },
        email: {
            required: true,
            regExp: /^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/,
            errorMsg: '请输入合法的邮箱地址'
        },
        qq_number: {
            required: false,
        },
        chat_number: {
            required: false,
        },
    },
    image: {
        fk_business_license_id: {
            required: true,
        },
        legal_person_identity_front_id: {
            required: true,
        },
        legal_person_identity_behind_id: {
            required: true,
        },
    }
}

class Views extends React.Component {

    constructor(props) {
        super(props)
        _self = this;
        this.state = {
            formStatus: FormStatus.EDIT,
            detail: {
                institution_name: '',
                busniess_number: '',
                legal_name: '',
                industry_type: '',
                nature: '',
                registered_capital: '',
                establishment_date: '',
                province: '',
                city: '',
                district: '',
                detail_address: '',
                business: '',
                advantage: '',
                the_applicant: '',
                the_applicant_job: '',
                mobile_phone: '',
                email: '',
                qq_number: '',
                chat_number: '',
                fk_business_license_id_imageUrl: '',
                legal_person_identity_behind_id_imageUrl: '',
                legal_person_identity_front_id_imageUrl: '',
                fk_business_license_id: '',
                legal_person_identity_front_id: '',
                legal_person_identity_behind_id: '',
                audit_state: ManagerService.MANAGER_AUDIT_STATE.PASSED,
                popout_state: ManagerService.MANAGER_SUCCESS_POPUP.INIT,
                state_reason: ''
            },
            industry: [],
            region: [],
            back: ''
        };
        this.state.back = this.props.navigation.state.params ? this.props.navigation.state.params.type : '';
    }

    componentWillMount() {

    }

    componentDidMount() {
        _self.load()
    }

    async load() {
        const {result, message, data} = await ManagerService.detail();
        if (result) {
            if (data) {
                DeviceEventEmitter.emit(Constants.LISTENER_LOGGING);
                _self.setState({
                    detail: {
                        ..._self.state.detail,
                        ...data.assetManager
                    },
                    industry: data.industry,
                    region: data.region
                }, () => {
                    _self.judgeState();
                    _self.validAll();
                })
            }
        } else {
            Toast.show(message);
        }
    }

    judgeState() {
        setTimeout(() => {
            if (_self.state.detail.audit_state === ManagerService.MANAGER_AUDIT_STATE.APPROVING) _self.skip('AuthApprove');
        }, 300);
    }

    validAll() {
        _self.setState({
            formStatus: FormEvent.isCompleted({
                ...validRule.base,
                ...validRule.contact,
                ...validRule.image
            }, _self.state.detail)
        })
    }

    skip(path, params) {
        _self.props.navigation.navigate(path, params);
    }

    async submit() {
        const {result, message} = await ManagerService.submit();
        Toast.show(message);
        if(result){
            DeviceEventEmitter.emit(Constants.LISTENER_LOGGING);
            _self.load();
        }
    }

    backForDemand() {
        const key = _self.props.navigation.state.params.prevState.pop().key;
        _self.props.navigation.goBack(key)
    }

    render() {
        return (
            <View style={base.baseOuter}>
                <NavBar
                    back={this.state.back !== 'demand'}
                    leftIcon={require('../../sources/icon_global_back.png')}
                    leftEvent={()=>this.backForDemand()}
                    host={this}
                    title={'认证资料'}/>
                {
                    this.state.detail.audit_state === ManagerService.MANAGER_AUDIT_STATE.INIT || this.state.detail.audit_state === ManagerService.MANAGER_AUDIT_STATE.UN_AUTH ?
                        <View style={[styles.tips, {backgroundColor: layout.MAIN_COLOR}]}>
                            <Text allowFontScaling={false} style={styles.tipText}>完善上述资料后，点击"立即认证"按钮提交审核，若审核通过，将以短信方式通知。</Text>
                        </View> : <View/>
                }
                {
                    this.state.detail.audit_state === ManagerService.MANAGER_AUDIT_STATE.REJECTED ?
                        <View style={[styles.tips, {backgroundColor: '#e79683'}]}>
                            <Text allowFontScaling={false} style={styles.tipText}>您的认证被驳回，原因如下：</Text>
                            <Text allowFontScaling={false} style={styles.tipText}>{this.state.detail.state_reason}</Text>
                        </View> : <View/>
                }
                {
                    this.state.detail.audit_state === ManagerService.MANAGER_AUDIT_STATE.PASSED && this.state.detail.popout_state === ManagerService.MANAGER_SUCCESS_POPUP.SHOW ?
                        <View style={[base.rowCC, styles.tips, {backgroundColor: '#8be784'}]}>
                            <Text allowFontScaling={false} style={styles.tipText}>恭喜！认证成功！</Text>
                        </View> : <View/>
                }
                <View style={styles.container}>
                    <View style={styles.box}>
                        <HorizontalMenu
                            onPress={() => this.skip('AuthForm', {
                                refresh: () => this.load(),
                                detail: this.state.detail,
                                validRule: validRule.base,
                                industry: this.state.industry,
                                region: this.state.region,
                                readOnly: this.state.detail.audit_state === ManagerService.MANAGER_AUDIT_STATE.APPROVING || this.state.detail.audit_state === ManagerService.MANAGER_AUDIT_STATE.PASSED
                            })}
                            text="企业基本信息"
                            icon={FormEvent.isValid(validRule.base, this.state.detail).result ? require('../../sources/icon_auth_star.png') : require('../../sources/icon_auth_star_empty.png')}/>
                        <HorizontalMenu
                            onPress={() => this.skip('AuthProForm', {
                                refresh: () => this.load(),
                                detail: this.state.detail,
                                validRule: validRule.contact,
                                readOnly: this.state.detail.audit_state === ManagerService.MANAGER_AUDIT_STATE.APPROVING || this.state.detail.audit_state === ManagerService.MANAGER_AUDIT_STATE.PASSED
                            })}
                            text="对接人信息"
                            icon={FormEvent.isValid(validRule.contact, this.state.detail).result ? require('../../sources/icon_auth_star.png') : require('../../sources/icon_auth_star_empty.png')}/>
                        <HorizontalMenu
                            onPress={() => this.skip('AuthImage', {
                                refresh: () => this.load(),
                                detail: this.state.detail,
                                validRule: validRule.image,
                                readOnly: this.state.detail.audit_state === ManagerService.MANAGER_AUDIT_STATE.APPROVING || this.state.detail.audit_state === ManagerService.MANAGER_AUDIT_STATE.PASSED
                            })}
                            text="证件资料"
                            icon={FormEvent.isValid(validRule.image, this.state.detail).result ? require('../../sources/icon_auth_star.png') : require('../../sources/icon_auth_star_empty.png')}
                            last={true}/>
                    </View>
                </View>
                {
                    this.state.detail.audit_state === ManagerService.MANAGER_AUDIT_STATE.UN_AUTH ||
                    this.state.detail.audit_state === ManagerService.MANAGER_AUDIT_STATE.INIT ||
                    this.state.detail.audit_state === ManagerService.MANAGER_AUDIT_STATE.REJECTED ?
                        <View style={styles.btnBox}>
                            <SubmitBtn
                                style={styles.btn}
                                onPress={() => this.submit()}
                                control={this.state.formStatus}
                                text={this.state.detail.audit_state === ManagerService.MANAGER_AUDIT_STATE.UN_AUTH ||
                                this.state.detail.audit_state === ManagerService.MANAGER_AUDIT_STATE.INIT ? '立即认证' : '重新认证'}/>
                        </View> :
                        <View/>
                }
            </View>
        )
    }
}

const styles = StyleSheet.create({
    tips: {
        paddingHorizontal: layout.GAP_HORIZONTAL_LARGE,
        paddingVertical: layout.GAP_VERTICAL_LARGE
    },
    tipText: {
        fontSize: layout.font(24),
        color: '#fff',
        lineHeight: layout.heightToFixed(36)
    },
    container: {
        flex: 1,
    },
    box: {
        backgroundColor: '#fff'
    },
    btnBox: {
        paddingHorizontal: layout.GAP_HORIZONTAL_SMALL,
        paddingVertical: layout.GAP_VERTICAL_SMALL
    },
    btn: {
        height: layout.height(90)
    }
})

//路由
const AuthList = {
    screen: Views,
    navigationOptions: {
        header: null,
    },
    name: 'AuthList',
    sign: true
};

export default AuthList;